package com.nekonomics
package types

import doobie.Meta
import zio.json.{JsonCodec, JsonDecoder, JsonEncoder}

enum UserRole {
  case Buyer, Seller, Admin
  
  override def toString: String = UserRole.toString(this)
} 

object UserRole {

  given JsonEncoder[UserRole] = JsonEncoder[String].contramap(toString)

  given JsonDecoder[UserRole] = JsonDecoder[String].mapOrFail(fromString)

  given Meta[UserRole] = Meta[String].tiemap(fromString)(toString)

  def fromString(s: String): Either[String, UserRole] = s.toLowerCase match {
    case "buyer" => Right(Buyer)
    case "seller" => Right(Seller)
    case "admin" => Right(Admin)
    case _ => Left(s"Invalid role: <$s>")
  }
  
  def toString(role: UserRole): String = role match {
    case Buyer => "buyer"
    case Seller => "seller"
    case Admin => "admin"
  }

}

